'use client'

import { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Skeleton } from '@/components/ui/skeleton'
import {
  Upload,
  Settings,
  Users,
  Package,
  BarChart3,
  FileText,
  ExternalLink,
  CheckCircle,
  X
} from 'lucide-react'
import { ToolUpload } from './tool-upload'
import { ToolManagement } from './tool-management'
import { UserManagement } from './user-management'
import { AdminDebugPanel } from './debug-panel'
import { useAdminData } from '@/hooks/use-admin-data'
import { useAuth } from '@/contexts/auth-context'

type TabType = 'overview' | 'review' | 'upload' | 'tools' | 'users' | 'settings' | 'debug'

export function AdminDashboard() {
  const [activeTab, setActiveTab] = useState<TabType>('overview')

  // 使用统一的数据管理Hook
  const adminData = useAdminData()

  const tabs = [
    { id: 'overview', label: '概览', icon: BarChart3 },
    { id: 'review', label: '工具审核', icon: FileText },
    { id: 'upload', label: '上传工具', icon: Upload },
    { id: 'tools', label: '工具管理', icon: Package },
    { id: 'users', label: '用户管理', icon: Users },
    { id: 'settings', label: '设置', icon: Settings },
    { id: 'debug', label: '调试', icon: Settings },
  ]

  const renderContent = () => {
    switch (activeTab) {
      case 'overview':
        return <OverviewTab adminData={adminData} />
      case 'review':
        return <ReviewTab adminData={adminData} />
      case 'upload':
        return <ToolUpload />
      case 'tools':
        return <ToolManagement />
      case 'users':
        return <UserManagement />
      case 'settings':
        return <SettingsTab />
      case 'debug':
        return <AdminDebugPanel />
      default:
        return <OverviewTab adminData={adminData} />
    }
  }

  return (
    <div className="space-y-6">
      {/* Tab Navigation */}
      <div className="border-b border-gray-200">
        <nav className="-mb-px flex space-x-8">
          {tabs.map((tab) => {
            const Icon = tab.icon
            return (
              <button
                key={tab.id}
                onClick={() => setActiveTab(tab.id as TabType)}
                className={`flex items-center gap-2 py-2 px-1 border-b-2 font-medium text-sm ${
                  activeTab === tab.id
                    ? 'border-blue-500 text-blue-600'
                    : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
                }`}
              >
                <Icon className="h-4 w-4" />
                {tab.label}
              </button>
            )
          })}
        </nav>
      </div>

      {/* Tab Content */}
      <div className="mt-6">
        {renderContent()}
      </div>
    </div>
  )
}

interface DashboardStats {
  totalTools: number
  deployedTools: number
  totalUsers: number
  pendingTools: number
  totalReviews: number
  totalFavorites: number
}

function OverviewTab({ adminData }: { adminData: any }) {
  const {
    stats = {
      totalTools: 0,
      approvedTools: 0,
      pendingTools: 0,
      rejectedTools: 0,
      totalUsers: 0,
      totalReviews: 0,
      totalFavorites: 0
    },
    loading = false,
    fetchFullStats
  } = adminData || {}

  const { user } = useAuth()

  useEffect(() => {
    if (fetchFullStats) {
      fetchFullStats()
    }
  }, [fetchFullStats])

  if (loading) {
    return (
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        {Array.from({ length: 4 }).map((_, i) => (
          <Card key={i}>
            <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
              <Skeleton className="h-4 w-20" />
              <Skeleton className="h-4 w-4" />
            </CardHeader>
            <CardContent>
              <Skeleton className="h-8 w-12 mb-2" />
              <Skeleton className="h-3 w-16" />
            </CardContent>
          </Card>
        ))}
      </div>
    )
  }

  if (!stats) {
    return (
      <div className="text-center py-8">
        <p className="text-gray-500">无法加载统计数据</p>
        <Button
          onClick={() => fetchFullStats && fetchFullStats()}
          className="mt-4"
        >
          重试
        </Button>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* 页面头部 */}
      <div className="flex justify-between items-center">
        <h2 className="text-xl font-semibold text-gray-900">系统概览</h2>
        <Button
          onClick={() => fetchFullStats && fetchFullStats()}
          variant="outline"
          size="sm"
          disabled={loading}
        >
          {loading ? '加载中...' : '刷新数据'}
        </Button>
      </div>

      {/* 主要统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">总工具数</CardTitle>
            <Package className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.totalTools}</div>
            <p className="text-xs text-muted-foreground">
              {stats.approvedTools} 个已通过
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">待审核工具</CardTitle>
            <FileText className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.pendingTools}</div>
            <p className="text-xs text-muted-foreground">
              需要审核处理
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">注册用户</CardTitle>
            <Users className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.totalUsers}</div>
            <p className="text-xs text-muted-foreground">
              平台用户总数
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">用户活跃度</CardTitle>
            <BarChart3 className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.totalReviews + stats.totalFavorites}</div>
            <p className="text-xs text-muted-foreground">
              评价和收藏总数
            </p>
          </CardContent>
        </Card>
      </div>

      {/* 详细统计 */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        <Card>
          <CardHeader>
            <CardTitle className="text-lg">工具状态分布</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              <div className="flex justify-between items-center">
                <span className="text-sm text-gray-600">已审核通过</span>
                <span className="font-medium">{stats.totalTools - stats.pendingTools}</span>
              </div>
              <div className="flex justify-between items-center">
                <span className="text-sm text-gray-600">等待审核</span>
                <span className="font-medium text-orange-600">{stats.pendingTools}</span>
              </div>
              <div className="flex justify-between items-center">
                <span className="text-sm text-gray-600">已部署</span>
                <span className="font-medium text-green-600">{stats.deployedTools}</span>
              </div>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="text-lg">用户互动统计</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-3">
              <div className="flex justify-between items-center">
                <span className="text-sm text-gray-600">总评价数</span>
                <span className="font-medium">{stats.totalReviews}</span>
              </div>
              <div className="flex justify-between items-center">
                <span className="text-sm text-gray-600">总收藏数</span>
                <span className="font-medium">{stats.totalFavorites}</span>
              </div>
              <div className="flex justify-between items-center">
                <span className="text-sm text-gray-600">平均每工具评价</span>
                <span className="font-medium">
                  {stats.totalTools > 0 ? (stats.totalReviews / stats.totalTools).toFixed(1) : '0'}
                </span>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>
    </div>
  )
}

function SettingsTab() {
  const [settings, setSettings] = useState({
    siteTitle: '工具聚合导航',
    siteDescription: '发现和分享优秀的web工具和游戏',
    allowUserSubmission: true,
    requireApproval: true,
    maxFileSize: '10',
    enableComments: true,
    enableRatings: true
  })
  const [saving, setSaving] = useState(false)

  const handleSave = async () => {
    setSaving(true)
    try {
      // 模拟保存设置
      await new Promise(resolve => setTimeout(resolve, 1000))
      alert('设置保存成功！')
    } catch (error) {
      alert('保存失败，请重试')
    } finally {
      setSaving(false)
    }
  }

  const handleInputChange = (key: string, value: any) => {
    setSettings(prev => ({ ...prev, [key]: value }))
  }

  return (
    <div className="space-y-6">
      {/* 基本设置 */}
      <Card>
        <CardHeader>
          <CardTitle>基本设置</CardTitle>
          <CardDescription>
            配置网站的基本信息
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div>
            <label className="text-sm font-medium">网站标题</label>
            <input
              type="text"
              value={settings.siteTitle}
              onChange={(e) => handleInputChange('siteTitle', e.target.value)}
              className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
            />
          </div>
          <div>
            <label className="text-sm font-medium">网站描述</label>
            <textarea
              value={settings.siteDescription}
              onChange={(e) => handleInputChange('siteDescription', e.target.value)}
              className="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              rows={3}
            />
          </div>
        </CardContent>
      </Card>

      {/* 工具管理设置 */}
      <Card>
        <CardHeader>
          <CardTitle>工具管理</CardTitle>
          <CardDescription>
            配置工具提交和审核相关设置
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex items-center justify-between">
            <div>
              <label className="text-sm font-medium">允许用户提交工具</label>
              <p className="text-xs text-gray-500">用户可以提交新的工具</p>
            </div>
            <input
              type="checkbox"
              checked={settings.allowUserSubmission}
              onChange={(e) => handleInputChange('allowUserSubmission', e.target.checked)}
              className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
            />
          </div>

          <div className="flex items-center justify-between">
            <div>
              <label className="text-sm font-medium">需要管理员审核</label>
              <p className="text-xs text-gray-500">新提交的工具需要审核后才能显示</p>
            </div>
            <input
              type="checkbox"
              checked={settings.requireApproval}
              onChange={(e) => handleInputChange('requireApproval', e.target.checked)}
              className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
            />
          </div>

          <div>
            <label className="text-sm font-medium">最大文件大小 (MB)</label>
            <input
              type="number"
              value={settings.maxFileSize}
              onChange={(e) => handleInputChange('maxFileSize', e.target.value)}
              className="mt-1 block w-32 px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              min="1"
              max="100"
            />
          </div>
        </CardContent>
      </Card>

      {/* 功能设置 */}
      <Card>
        <CardHeader>
          <CardTitle>功能设置</CardTitle>
          <CardDescription>
            启用或禁用特定功能
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex items-center justify-between">
            <div>
              <label className="text-sm font-medium">启用评论功能</label>
              <p className="text-xs text-gray-500">用户可以对工具进行评论</p>
            </div>
            <input
              type="checkbox"
              checked={settings.enableComments}
              onChange={(e) => handleInputChange('enableComments', e.target.checked)}
              className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
            />
          </div>

          <div className="flex items-center justify-between">
            <div>
              <label className="text-sm font-medium">启用评分功能</label>
              <p className="text-xs text-gray-500">用户可以对工具进行评分</p>
            </div>
            <input
              type="checkbox"
              checked={settings.enableRatings}
              onChange={(e) => handleInputChange('enableRatings', e.target.checked)}
              className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
            />
          </div>
        </CardContent>
      </Card>

      {/* 系统信息 */}
      <Card>
        <CardHeader>
          <CardTitle>系统信息</CardTitle>
          <CardDescription>
            当前系统状态和版本信息
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-2">
          <div className="grid grid-cols-2 gap-4 text-sm">
            <div>
              <span className="font-medium">版本:</span> v0.1.0
            </div>
            <div>
              <span className="font-medium">环境:</span> {process.env.NODE_ENV}
            </div>
            <div>
              <span className="font-medium">数据库:</span> JSON 文件存储
            </div>
            <div>
              <span className="font-medium">认证:</span> 开发环境模式
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 保存按钮 */}
      <div className="flex justify-end">
        <Button
          onClick={handleSave}
          disabled={saving}
          className="px-6"
        >
          {saving ? '保存中...' : '保存设置'}
        </Button>
      </div>
    </div>
  )
}

// 工具审核标签页
function ReviewTab({ adminData }: { adminData: any }) {
  const {
    pendingTools = [],
    loading = false,
    approveTool,
    rejectTool,
    refreshData
  } = adminData || {}

  const handleApprove = async (toolId: string) => {
    if (!approveTool) return
    const result = await approveTool(toolId)
    if (result.success) {
      alert('工具审核通过！')
    } else {
      alert(`审核失败: ${result.error}`)
    }
  }

  const handleReject = async (toolId: string) => {
    if (!rejectTool) return
    const result = await rejectTool(toolId)
    if (result.success) {
      alert('工具已拒绝！')
    } else {
      alert(`拒绝失败: ${result.error}`)
    }
  }

  if (loading) {
    return (
      <div className="space-y-4">
        {Array.from({ length: 3 }).map((_, i) => (
          <Card key={i}>
            <CardContent className="p-6">
              <div className="animate-pulse">
                <div className="h-6 bg-gray-200 rounded w-1/3 mb-4"></div>
                <div className="h-4 bg-gray-200 rounded w-full mb-2"></div>
                <div className="h-4 bg-gray-200 rounded w-2/3 mb-4"></div>
                <div className="flex gap-2">
                  <div className="h-8 bg-gray-200 rounded w-20"></div>
                  <div className="h-8 bg-gray-200 rounded w-20"></div>
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    )
  }

  if (pendingTools.length === 0) {
    return (
      <Card>
        <CardContent className="p-12 text-center">
          <FileText className="h-12 w-12 text-gray-400 mx-auto mb-4" />
          <h3 className="text-lg font-medium text-gray-900 mb-2">
            暂无待审核工具
          </h3>
          <p className="text-gray-500">
            所有提交的工具都已审核完成
          </p>
        </CardContent>
      </Card>
    )
  }

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <h2 className="text-xl font-semibold text-gray-900">
          待审核工具 ({pendingTools.length})
        </h2>
        <Button
          onClick={() => refreshData && refreshData()}
          variant="outline"
          size="sm"
          disabled={loading}
        >
          {loading ? '加载中...' : '刷新列表'}
        </Button>
      </div>

      <div className="space-y-4">
        {pendingTools.map((tool) => (
          <Card key={tool.id}>
            <CardContent className="p-6">
              <div className="flex justify-between items-start">
                <div className="flex-1">
                  <div className="flex items-center gap-2 mb-2">
                    <h3 className="text-lg font-semibold text-gray-900">
                      {tool.title}
                    </h3>
                    <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800">
                      待审核
                    </span>
                  </div>

                  <p className="text-gray-600 mb-3">
                    {tool.description}
                  </p>

                  <div className="flex items-center gap-4 text-sm text-gray-500 mb-4">
                    <span>提交者: {tool.user?.name || '未知用户'}</span>
                    <span>分类: {tool.category?.name || '未知分类'}</span>
                    <span>提交时间: {new Date(tool.createdAt).toLocaleDateString()}</span>
                  </div>

                  <div className="flex items-center gap-2">
                    <Button
                      onClick={() => window.open(tool.url, '_blank')}
                      variant="outline"
                      size="sm"
                    >
                      <ExternalLink className="h-4 w-4 mr-2" />
                      预览工具
                    </Button>
                    <Button
                      onClick={() => handleApprove(tool.id)}
                      variant="default"
                      size="sm"
                      className="bg-green-600 hover:bg-green-700"
                    >
                      <CheckCircle className="h-4 w-4 mr-2" />
                      审核通过
                    </Button>
                    <Button
                      onClick={() => handleReject(tool.id)}
                      variant="destructive"
                      size="sm"
                    >
                      <X className="h-4 w-4 mr-2" />
                      拒绝
                    </Button>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  )
}
